<?php

class UsersController extends AppController {

    var $name = 'Users';
    var $helpers = array('Html', 'Session', 'Form', 'Ajax', 'Facebook.Facebook');
    var $uses = array('User');
    var $components = array('Auth', 'Email');

    function beforeFilter() {
        echo __METHOD__;
        $this->Auth->allow(array(
            'facebook',
            'signup',
            'captcha_image',
            'captcha_audio',
            'login',
            'logout',
            'profile',
            'activate_account',
            'forgetpassword',
            'reset_password'
        ));
        $this->Auth->loginRedirect = array(
            'controller' => 'users',
            'action' => 'dashboard'
        );
        $this->Auth->logoutRedirect = array(
            'controller' => 'users',
            'action' => 'login'
        );
        $this->Auth->loginError = "No, you fool! That's not the right password!";
        $this->Auth->authError = "Sorry, you are lacking access.";
        parent::beforeFilter();
    }

    function facebook() {
        echo __METHOD__;
        if (!$this->Auth->User('id')) {
            $fb_id = $this->Connect->user();
            if (isset($fb_id) and ($fb_id)) {
                $headers = get_headers('https://graph.facebook.com/' . $fb_id['id'] . '/picture?type=normal', 1);
                // just a precaution, check whether the header isset...
                if (isset($headers['Location'])) {
                    $url = $headers['Location']; // string
                } else {
                    $url = false; // nothing there? .. weird, but okay!
                }
                $user['User'] = array(
                    'provider' => 'facebook',
                    'provider_id' => $fb_id['id'],
                    'provider_profile_image' => 'http://graph.facebook.com/' . $fb_id['id'] . '/picture?type=normal',
                    'img' => $url,
                    'name' => $fb_id['name'],
                    'email' => $fb_id['email'],
                    'other' => $fb_id
                );
                if (isset($user) and sizeof($user) and ($user)) {
                    $this->Session->write('api_user', $user);
                    $this->redirect('signup');
                }
            } else {
                $this->redirect('login');
            }
        }
    }

    function captcha_image() {
        echo __METHOD__;
        $this->Captcha->image();
    }

    function captcha_audio() {
        echo __METHOD__;
        $this->Captcha->audio();
    }

    function signup() {
        echo __METHOD__;
        $api_user = $this->Session->read('api_user');
        if (isset($api_user) and sizeof($api_user) and ($api_user)) {
            $check_exited_user = $this->User->find('first', array(
                'conditions' => '(User.provider = "' . $api_user['User']['provider'] . '" 
											and 
										User.provider_id = "' . $api_user['User']['provider_id'] . '"
											and
										User.email="' . $api_user['User']['email'] . '")
											or
										(User.email="' . $api_user['User']['email'] . '")
											and
									   User.is_verified=1',
                'fields' => 'User.*'
                    ));
            if (isset($check_exited_user) and sizeof($check_exited_user) and ($check_exited_user)) {
                if ((isset($check_exited_user['User']['provider']) and ($check_exited_user['User']['provider'])) and (isset($check_exited_user['User']['provider_id']) and ($check_exited_user['User']['provider_id']))) {
                    
                } else {
                    $this->data['User']['id'] = $check_exited_user['User']['id'];
                    $this->data['User']['provider'] = $api_user['User']['provider'];
                    $this->data['User']['provider_id'] = $api_user['User']['provider_id'];
                    $this->data['User']['provider_profile_image'] = $api_user['User']['provider_profile_image'];
                    $this->User->Save($this->data['User']);
                }
                $login['User']['username'] = $check_exited_user['User']['username'];
                $login['User']['password'] = $check_exited_user['User']['password'];
                $this->data = $login['User'];
                $this->Auth->login($this->data);
                $user = $this->Auth->User();
                $this->Session->delete('api_user');
                $this->redirect(array(
                    'controller' => 'users',
                    'action' => 'profile',
                    $this->Auth->User('slug')
                ));
            } else {
                if ($api_user['User']['provider'] == "facebook") {
                    if (isset($api_user['User']['other']['work']) and ($api_user['User']['other']['work'])
                            and
                            isset($api_user['User']['other']['work']['0']['employer']['name'])) {
                        $about = $api_user['User']['other']['work']['0']['employer']['name'];
                    } elseif (isset($api_user['User']['other']['work']) and ($api_user['User']['other']['work'])
                            and
                            $api_user['User']['other']['work']['0']['description']['name']) {
                        $about = $about . ' ' . $api_user['User']['other']['work']['0']['description']['name'];
                    } else {
                        $about = "";
                    }
                    $acount_link = '' . "https://www.facebook.com/profile.php?id = " . $api_user['User']['provider_id'] . '';
                } else {
                    $about = "";
                    $acount_link = "";
                }
                $api_user['User']['about'] = $about;
                $api_user['User']['acount_link'] = $acount_link;
                $this->Session->write('api_user', $api_user);
                $this->redirect(array(
                    'controller' => 'users',
                    'action' => 'login'
                ));
            }
        } elseif (isset($this->data) and sizeof($this->data) and empty($this->data) == false) {
            $this->set('data', $this->data);
            if (isset($this->data['User']['captcha_code']) and ($this->data['User']['captcha_code'] == 10)) {
                if ((isset($this->data['User']) and ($this->data['User'])) and ($this->data['User']['username'])) {
                    $subscribe_email = $this->data['User']['username'];
                    $userregistered = array();
                    $userregistered = $this->User->find('first', array(
                        'conditions' => 'User.username = "' . $subscribe_email . '"',
                        'fields' => 'User.id'
                            ));
                    if (isset($userregistered['User']['id']) and sizeof($userregistered['User']['id']) and ($userregistered['User']['id'])) {
                        $this->Session->setFlash('Email already in use');
                        $this->render('login');
                    } else {
                        if (isset($this->data['User']['password']) and
                                ($this->data['User']['password'] == $this->Auth->password($this->data['User']['confirm_password']))) {
                            $this->data['User']['name'] = $this->data['User']['first_name'] . '' . $this->data['User']['last_name'];
                            $this->data['User']['email'] = $this->data['User']['username'];
                            $slug_value = str_replace(' ', '_', strtolower($this->data['User']['name']));
                            $User_Slug = $this->User->generateSlug($slug_value);
                            $this->data['User']['slug'] = $User_Slug;
                            $this->data['User']['hash'] = $this->__generateKey('User');
                            if (isset($this->data['User']['img']) and ($this->data['User']['img'])) {
                                $img = $this->url_upload('User', $this->data['User']['img']);
                                $this->data['User']['img'] = $img;
                            }
                            $this->data['User']['last_login'] = date('Y-m-d h:i:s');
                            if (!$this->Connect->user('id')) {
                                $this->data['User']['is_verified'] = '0';
                            } else {
                                $this->data['User']['is_verified'] = '1';
                            }
                            $this->data['User']['role'] = 'customer';
                            $this->User->create();
                            $this->User->save($this->data['User']);
                            $user_id = $this->User->getLastInsertId();
                            if (!$this->Connect->user('id')) {
                                $get_subject['MessageSubject']['name'] = 'WonderE account verification mail.';
                                $website_image_url = Configure::read('Website.image_url');
                                $mail_message = '
											
												Dear [user_name],<br>
												
												Please click on this [activate_link] to activate your account.<br>
												After clicking the link you can login to use our Services.<br>
												
												
												
												Thank you,<br><br>
												
												WonderE Team Support';

                                $user_name = $this->data['User']['name']; // Becouse no user name entering.
                                $activation_link = $website_image_url . 'users/activate_account/' . $this->data['User']['hash'];
                                $mail_message = str_replace("[user_name]", $user_name, $mail_message);
                                $mail_message = str_replace("[activate_link]", $activation_link, $mail_message);
                                $this->data['Message']['dec'] = $mail_message;
                                $user_email = $this->data['User']['email'];
                                //$mail_persons[$user_email] = $user_name;
                                $this->Email->useremail($user_email, $get_subject['MessageSubject']['name'], $this->data['Message']['dec']);
                                //$this->__send_mail($mail_persons,$get_subject['MessageSubject']['name'], $this->data['Message']['dec']);
                                $this->Session->setFlash('Activation Link has been Sent to your mail.
											 Please Click on Link to activate and check spam also.');
                                $this->redirect(array(
                                    'controller' => 'users',
                                    'action' => 'login'
                                ));
                            } else {
                                $this->data = $this->data['User'];
                                $this->Auth->login($this->data);
                                $this->redirect("dashboard");
                            }
                        } else {
                            $this->Session->setFlash('Password are not matched. Please try again.');
                            $this->redirect(array(
                                'controller' => 'users',
                                'action' => 'login'
                            ));
                        }
                    }
                }
            } else {
                $this->Session->setFlash('Please Enter Valid Data.');
                $this->redirect(array(
                    'controller' => 'users',
                    'action' => 'login'
                ));
            }
        }
        exit;
    }

    function activate_account($hash = null) {
        echo __METHOD__;
        if (isset($hash) and $hash) {
            $sql_check = 'select * from users where hash = "' . $hash . '" and is_verified = "1"';
            $result = $this->User->query($sql_check);
            $row = count($result);
            if ($row >= 1) {
                //echo "If 1";
                //exit;
                $this->Session->setFlash('Your Account is already activated. Please Login!');
                $this->redirect(array(
                    'controller' => 'users',
                    'action' => 'login'
                ));
            } else {
                //echo "If else 1";
                //exit;
                $sql = 'update users set is_verified = 1 where hash = "' . $hash . '"';
                $result_set = $this->User->query($sql);
                if ($result_set) {
                    $this->Session->setFlash('Your Account has been Activated. Please login');
                    $this->redirect(array(
                        'controller' => 'users',
                        'action' => 'login'
                    ));
                } else {
                    $this->Session->setFlash('Please Use Valid Link To Activate Account.');
                    $this->redirect(array(
                        'controller' => 'users',
                        'action' => 'login'
                    ));
                }
            }
        } else {
            //echo "If hash else 1";
            //exit;
            $this->Session->setFlash('Please Use Valid Link To Activate Account.');
            $this->redirect(array(
                'controller' => 'users',
                'action' => 'login'
            ));
        }
    }

    function login() {
        echo __METHOD__;
        if ($this->Auth->user()) {
            if (!empty($this->data) && $this->data['User']['remember_me']) {
                $cookie = array();
                $cookie['username'] = $this->data['User']['username'];
                $cookie['password'] = $this->data['User']['password'];
                $this->Cookie->write('Auth.User', $cookie, true, '+2 weeks');
                unset($this->data['User']['remember_me']);
            }
            $this->redirect($this->Auth->redirect());
        } elseif (empty($this->data)) {
            $cookie = $this->Cookie->read('Auth.User');
            if (!is_null($cookie)) {
                if ($this->Auth->login($cookie)) {
                    //  Clear auth message, just in case we use it.
                    $this->Session->del('Message.auth');
                    $this->redirect($this->Auth->redirect());
                } else { // Delete invalid Cookie
                    $this->Cookie->del('Auth.User');
                }
            } elseif ($this->Session->read('api_user')) {
                $user = $this->Session->read('api_user');
                unset($user['User']['other']);
                $this->Set('user', $user);
                $this->Session->delete('api_user');
            } elseif ($this->Connect->user('id')) {
                $this->redirect(array(
                    'action' => 'facebook'
                ));
            }
        }
    }

    function profile($slug = "") {
        echo __METHOD__;
        $user = $this->User->findBySlug($slug, array(
            'fields' => 'User.*'
                ));
        $this->Set('user', $user);
        $user_id = $user['User']['id'];
        $this->paginate['ProductReview'] = array(
            'conditions' => 'ProductReview.user_id="' . $user_id . '"',
            'limit' => 24,
            'fields' => array(
                'ProductReview.*'
            ),
            'order' => 'ProductReview.created Desc'
        );
        $ProductReviews = $this->paginate('ProductReview');
        if (isset($ProductReviews) and ($ProductReviews)) {
            $x = 0;
            foreach ($ProductReviews as $ProductReview) {
                $product = $this->wisn_product($ProductReview['ProductReview']['product_id']);
                $user = $this->User->findbyId($ProductReview['ProductReview']['user_id']);
                $ProductReviews[$x]['ProductReview']['user'] = $user['User'];
                $ProductReviews[$x]['ProductReview']['Product'] = $product['Product'];
                $x++;
            }
            $this->Set('ProductReviews', $ProductReviews);
        }
        $this->Set('ProductReviews', $ProductReviews);
        $user_wish_listes = $this->Wishlist->find('all', array(
            'conditions' => 'Wishlist.user_id="' . $user_id . '" and Wishlist.access="public"',
            'fields' => 'Wishlist.name,Wishlist.id '
                ));
        if (isset($user_wish_listes) and ($user_wish_listes)) {
            $x = 0;
            foreach ($user_wish_listes as $user_wish_list) {
                $this->paginate['WishlistProduct'] = array(
                    'conditions' => 'WishlistProduct.wishlist_id="' . $user_wish_list['Wishlist']['id'] . '"',
                    'fields' => array(
                        'WishlistProduct.product_id'
                    ),
                    'order' => 'WishlistProduct.created Desc'
                );
                $WishlistProducts = $this->paginate('WishlistProduct');
                if (isset($WishlistProducts) and ($WishlistProducts)) {
                    $vb = 0;
                    foreach ($WishlistProducts as $WishlistProduct) {
                        $get_product = $this->wisn_product($WishlistProduct['WishlistProduct']['product_id']);
                        $WishlistProducts[$vb]['WishlistProduct']['Product'] = $get_product['Product'];
                        $vb++;
                    }
                }
                $user_wish_listes[$x]['Wishlist']['Products'] = $WishlistProducts;
                $x++;
            }
            //pr($user_wish_listes);
            //exit;
            $this->Set('user_wish_listes', $user_wish_listes);
        }
        //exit;
    }

    function dashboard($slug = "") {
        echo __METHOD__;
        $user_id = $this->Auth->User('id');
        $paypal_registred = $this->_is_paypal_registred($user_id);
        $this->Set('paypal_registred', $paypal_registred);
    }

    function account_setting() {
        echo __METHOD__;
        $login_user_id = $this->Auth->User('id');
        $user = $this->User->findById($login_user_id);
        $this->Set('user', $user);
        if (isset($this->data) and ($this->data)) {
            if (isset($this->data['User']) and ($this->data['User'])) {
                $this->data['User']['id'] = $this->__get_user_id($this->data['User']['hash']);
                $this->User->save($this->data['User']);
                if (isset($this->data['User']['imgImage']) and ($this->data['User']['imgImage']) and ($this->data['User']['imgImage']['name'])) {
                    $image = $this->data['User']['imgImage'];
                    $this->data['User']['id'] = $this->data['User']['id'];
                    $Job_image_name = str_replace(' ', '_', $image['name']);
                    $job_image_name_explode = explode('.', $Job_image_name);
                    //pr($Job_image_name);
                    //exit;
                    $job_image_name_explode_start_name = $job_image_name_explode[0];
                    $job_image_name_explode_ext = $job_image_name_explode[1];
                    $job_image_name_filtered = date('ymd') . time() . "." . $job_image_name_explode_ext;
                    $this->data['User']['img'] = strtolower($job_image_name_filtered);
                    $image['name'] = strtolower($job_image_name_filtered);
                    ;
                    $upload_file = $this->upload_img("", $image, 'User');
                    $this->User->save($this->data['User']);
                }
                $this->redirect(array(
                    'controller' => 'users',
                    'action' => 'dashboard'
                ));
                $this->Session->setFlash('Your account Settings has been saved.');
            }
        }
    }

    function logout() {
        echo __METHOD__;
        $date = date('Y-m-d h:i:s');
        $userid = $this->Auth->User('id');
        $this->User->updateAll(array(
            'User.last_login' => "'" . $date . "'"
                ), array(
            'User.id' => $userid
        ));
        $this->Session->destroy('user');
        $this->redirect($this->Auth->logout());
    }

    function change_password() {
        echo __METHOD__;
        if (empty($this->data) == false) {
            $id = $this->Session->read('Auth.User.id');
            $user = $this->User->find('first', array(
                'conditions' => array(
                    'id' => $id
                )
                    ));
            $this->set('user', $user);
            if (!empty($this->data['User'])) {
                if ($user['User']['password'] == $this->Auth->password($this->data['User']['passwordenter'])) {
                    $this->data['User']['id'] = $id;
                    $this->data['User']['password'] = $this->Auth->password($this->data['User']['passwordn']);
                    $this->User->save($this->data['User']);
                    $this->Session->setFlash('Password has been changed.');
                    $this->redirect(array(
                        'controller' => 'users',
                        'action' => 'profile',
                        $this->Auth->User('slug')
                    ));
                } else {
                    $this->Session->setFlash('Typed passwords did not match.');
                }
            }
        }
    }

    function forgetpassword() {
        echo __METHOD__;
        if (isset($this->data) and empty($this->data) == false) {
            $post = $this->data;
            $this->Set('post', $post);
            $user_email = $this->data['User']['email'];
            $UserDetails = $this->User->findByEmail($user_email);
            $num_users = sizeof($UserDetails['User']);
            if (sizeof($UserDetails['User'])) {
                $user_id = $UserDetails['User']['id'];
                $user_name = $UserDetails['User']['email'];
                $user_email = $UserDetails['User']['email'];
                $user_hash_key = $this->__generateKey('User');
                $current_entry = $this->Forgot->find('all', array(
                    'conditions' => 'Forgot.user_id = ' . $user_id
                        ));
                if (isset($current_entry) and sizeof($current_entry)) {
                    $query = "UPDATE forgots SET user_hash = '" . $user_hash_key . "' WHERE user_id = " . $user_id;
                    $result = $this->Forgot->query($query);
                } else {
                    $query = "INSERT INTO forgots (user_id,user_name,user_email, user_hash, created) VALUES ('" . $user_id . "', '" . $user_name . "', '" . $user_email . "', '" . $user_hash_key . "', now())";
                    $result = $this->Forgot->query($query);
                }
                $mail_subject = 'Forget Password Confermation Link from WonderE Inc.';
                /*
                 * <----Here is Code for template of email file open and replace Candidate name and metter of Email----->
                 */
                $current_directory = getcwd();
                $website_url = Configure::read('Website.url');
                $website_image_url = Configure::read('Website.image_url');
                $email_directory = $website_image_url;
                //$file = fopen($email_directory . "/emails/forget_password_confirmation_link.html", "r");
                $mail_message = 'Forget password confirmation link from Need to?

										Dear [user_name],
																
										Please click on this [activate_link] to reset your password. After authenticating you will be update password.
										
										Thank you,
										
										WonderE Team Support';
                $mail_message = str_replace("[user_name]", $user_name, $mail_message);
                $link = $website_url . 'users/reset_password/' . $user_hash_key;
                $mail_message = str_replace("[activate_link]", $link, $mail_message);
                $mail_persons[$user_email] = $user_name;
                $this->__send_mail($mail_persons, $mail_subject, $mail_message, $mail_from_email = "", $mail_from_name = "");
                $this->Session->setFlash('An email has been sent to your email address with instructions to reset your password.');
                $this->redirect(array(
                    'controller' => 'users',
                    'action' => 'forgetpassword'
                ));
            } else {
                //User does not exist
                $this->Session->setFlash('Please enter a valid email address. In case of any problem, please contact the administrator.');
            }
            //exit;
        } else {
            $this->Set('post', null);
            $this->render('forgetpassword');
        }
    }

    function reset_password($hashkey = '') {
        echo __METHOD__;
        if (!$hashkey) {
            $this->Session->setFlash('The link you have followed is incorrect.');
            $this->redirect(array(
                'controller' => 'users',
                'action' => 'login'
            ));
            //exit;
        } else {
            $this->set('user_hash', $hashkey);
        }
        $entry = $this->Forgot->find('all', array(
            'conditions' => 'Forgot.user_hash = "' . $hashkey . '"'
                ));
        if (!sizeof($entry)) {
            $this->Session->setFlash('The link you have followed is incorrect or has expired.');
            $this->redirect(array(
                'controller' => 'users',
                'action' => 'login'
            ));
            exit;
        } else {
            if (empty($this->data) == false) {
                //pr($this->data);
                //exit;
                $user_details = $entry[0];
                $user_id = $user_details['Forgot']['user_id'];
                //pr($this->data);
                if ($this->data['Forgot']['user_pass'] and
                        ($this->data['Forgot']['user_pass'] == $this->data['Forgot']['confirm_user_pass'])) {
                    $new_pass = $this->Auth->password($this->data['Forgot']['confirm_user_pass']);
                    $query = "UPDATE users SET password = '" . $new_pass . "' WHERE id = " . $user_id;
                    $result = $this->User->query($query);
                    if ($result) {
                        $query2 = "DELETE FROM forgots WHERE user_hash = '" . $hashkey . "'";
                        $result2 = $this->User->query($query2);
                        $this->Session->setFlash('Password reset successfully. You can now login using new password.');
                        $this->redirect(array(
                            'controller' => 'users',
                            'action' => 'login'
                        ));
                        exit;
                    }
                } else {
                    $this->Session->setFlash('Password and confirm password do not match');
                }
            } else {
                if (isset($hashkey))
                    $this->set('user_hash', $hashkey);
            }
        }
    }

    function orders($type = "") {
        echo __METHOD__;
        $user_id = $this->Session->read('Auth.User.id');
        if (isset($type) and ($type)) {
            if ($type == 'paid') {
                $conditions = "Order.payment_status = '1' and Order.customer_id = '" . $user_id . "'";
            } elseif ($type == 'unpaid') {
                $conditions = "Order.payment_status = '0' and Order.customer_id = '" . $user_id . "'";
            }
            $this->Set('type', $type);
        } else {
            //secho "hu";
            $last_7_days = $this->_last_dates(7, 'd');
            $conditions = "Order.payment_status = '1' and Order.created<='" . date('Y-m-d') . "' and Order.created>='" . $last_7_days . "' and Order.customer_id = '" . $user_id . "'";
        }
        if (isset($this->data['Order']['TrackingId']) and ($this->data['Order']['TrackingId'])) {
            $user_id = $this->Session->read('Auth.User.id');
            $conditions = "Order.tracking_id = '" . $this->data['Order']['TrackingId'] . "' and Order.customer_id = '" . $user_id . "'";
        }
        $this->paginate['Order'] = array(
            'conditions' => $conditions,
            'limit' => 10,
            'order' => "Order.id DESC"
        );
        $Order_list = $this->paginate('Order');
        $this->set('Order_list', $Order_list);
    }

    function order_detail($tracking_order = "") {
        echo __METHOD__;
        if (isset($tracking_order) and ($tracking_order)) {
            $order_detail = $this->Order->findByTrackingId($tracking_order);
            $this->Set('order_detail', $order_detail);
            $order_items = $this->OrderItem->find('all', array(
                'conditions' => 'OrderItem.order_id=' . $order_detail['Order']['id'] . '',
                'fields' => ' OrderItem.*'
                    ));
            if (isset($order_items) and ($order_items)) {
                $x = 0;
                foreach ($order_items as $order_item) {
                    $product = $this->Product->findById($order_item['OrderItem']['product_id']);
                    $order_items[$x]['Product'] = $product['Product'];
                    $x++;
                }
                $this->Set('order_items', $order_items);
            }
        } else {
            $this->redirect(array(
                'action' => 'orders'
            ));
        }
    }

    function add_address() {
        echo __METHOD__;
        if (isset($this->params['named']['address']) and ($this->params['named']['address'])) {
            $address_id = $this->params['named']['address'];
            if (isset($address_id) and ($address_id)) {
                $address_id = base64_decode($address_id);
                $Edit_address = $this->Address->findById($address_id);
                $this->Set('Edit_address', $Edit_address);
            }
        }
        $list_countries = $this->__list_countries();
        $this->Set('list_countries', $list_countries);
        if (isset($this->data) and ($this->data)) {
            if (isset($this->data['Address']) and ($this->data['Address'])) {
                $this->data['Address']['user_id'] = $this->Auth->User('id');
                $this->Address->Save($this->data['Address']);
                if (isset($this->data['Address']['id']) and ($this->data['Address']['id'])) {
                    $message = "Address has been updated.";
                } else {
                    $message = "A New Address Has been Added to Your Account.";
                }
                $this->Session->setFlash($message);
                $this->redirect(array(
                    'controller' => 'users',
                    'action' => 'dashboard'
                ));
            }
        }
    }

    function manage_address_book() {
        echo __METHOD__;
        $address = $this->Address->find('all', array(
            'conditions' => 'Address.user_id="' . $this->Auth->User('id') . '"'
                ));
        $this->Set('address', $address);
    }

    function customer_Mails() {
        echo __METHOD__;
        $user_id = $this->Auth->User('id');
        $Sent_messages = $this->__Seller_Sentmail($user_id, "", "");
        //pr($Sent_messages);
        //exit;
        $this->Set('messages', $Sent_messages);
        $customer_Recievedmail = $this->__Seller_Recievedmail($user_id);
        /* Seller_Recievedmail */
        //pr($customer_Recievedmail);
        //exit;
        $this->Set('customer_Recievedmail', $customer_Recievedmail);
        if (isset($this->data) and ($this->data)) {
            if (isset($this->data['Message']['Sent']) and ($this->data['Message']['Sent'])) {
                $Sentcount = explode('_', $this->data['Message']['Sent']);
                $date = $this->_last_dates($Sentcount[0], $Sentcount[1]);
                $Sent_messages = $this->__Seller_Sentmail($user_id, $date, date('Y-m-d'));
                $this->Set('messages', $Sent_messages);
            }
            if (isset($this->data['Message']['Recieved']) and ($this->data['Message']['Recieved'])) {
                $Sentcount = explode('_', $this->data['Message']['Recieved']);
                $date = $this->_last_dates($Sentcount[0], $Sentcount[1]);
                $__Seller_Recievedmail = $this->__Seller_Recievedmail($user_id, $date, date('Y-m-d'));
                $this->Set('Seller_Recievedmail', $__Seller_Recievedmail);
            }
        }
    }

    function customer_do_mail($sellerhash = "", $order_id = "") {
        echo __METHOD__;
        $Mail_subjects = $this->__list_message_subjects('');
        $this->Set('subjects', $Mail_subjects);
        $this->Set('order_id', $order_id);
        if (isset($sellerhash) and ($sellerhash)) {
            $Userdetails = $this->User->find('first', array(
                'conditions' => 'User.hash="' . $sellerhash . '"'
                    ));
            if (isset($Userdetails) and ($Userdetails)) {
                $this->Set('Userdetails', $Userdetails);
            } else {
                $this->redirect(array(
                    'action' => 'seller_Mails'
                ));
            }
        }
        if (isset($this->data) and ($this->data)) {
            //pr($this->data);
            //exit;
            if (isset($this->data['Message']) and ($this->data['Message'])) {
                $maile_sender_id = $this->Auth->User('id');
                $maile_sender_id_detail = $this->User->findById($maile_sender_id, array(
                    'fields' => 'User.*'
                        ));
                $this->data['Message']['hash'] = $this->__generateKey('Message');
                $get_subject = $this->MessageSubject->findById($this->data['Message']['subject_id']);
                $this->data['Message']['to_email'] = $this->data['Message']['email'];
                $exp_hash = explode('@', $this->data['Message']['email']);
                $user_id = $this->User->findByHash($exp_hash[0], array(
                    'fields' => 'User.*'
                        ));
                $this->data['Message']['to_user_id'] = $user_id['User']['id'];
                $this->data['Message']['from_email'] = $maile_sender_id_detail['User']['hash'] . wondere_email_domain;
                $this->data['Message']['from_user_id'] = $this->Auth->User('id');
                //pr($this->data['Message']);
                //exit;
                $this->Message->save($this->data['Message']);
                $last_id = $this->Message->getLastInsertId();
                if (isset($this->data['Message']['attachment']) and ($this->data['Message']['attachment']) and ($this->data['Message']['attachment']['name'])) {
                    $image = $this->data['Message']['attachment'];
                    $this->data['Message']['id'] = $last_id;
                    $Job_image_name = str_replace(' ', '_', $image['name']);
                    $job_image_name_explode = explode('.', $Job_image_name);
                    $job_image_name_explode_start_name = $job_image_name_explode[0];
                    $job_image_name_explode_ext = $job_image_name_explode[1];
                    $job_image_name_filtered = date('ymd') . time() . "." . $job_image_name_explode_ext;
                    $this->data['Message']['attach'] = strtolower($job_image_name_filtered);
                    $image['name'] = $this->data['Message']['attach'];
                    $upload_file = $this->upload_img($last_id, $image, 'MessageAttchment');
                    $this->Message->save($this->data['Message']);
                }
                $direc = getcwd();
                $attch = $direc . '/img' . '/MessageAttchment/' . $last_id . '/' . $this->data['Message']['attach'];
                $mail_persons[$user_id['User']['email']] = $user_id['User']['name'];
                $this->__send_mail($mail_persons, $get_subject['MessageSubject']['name'], $this->data['Message']['dec'], $this->data['Message']['from_email'], $maile_sender_id_detail['User']['name'], $attch);
                $this->redirect(array(
                    'action' => 'index'
                ));
            }
        }
    }

}

?>